package com.example.demo.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * ❤️❤️❤️❤️❤️
 * 源数据单位: 分
 * 支持类型: Integer, Long, BigDecimal
 * 返回格式: 分转元, 且使用金额分位符, 如: 0.00元, 1,234,500.00元, 1,234,567.89元
 *
 * PS:
 * ✅ #,##0.00
 * ❌ #,###.##
 *
 * @author Shanks
 * @date 2020-11-07
 */
@Slf4j
public class Fen2YuanCurrencySerializer extends JsonSerializer<Number> {

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#,##0.00");
    private static final BigDecimal HUNDRED = new BigDecimal("100");

    @Override
    public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        BigDecimal value = BigDecimal.ZERO;
        if (Objects.nonNull(number)) {
            value = new BigDecimal(String.valueOf(number)).divide(HUNDRED, 2, RoundingMode.HALF_UP);
        }
        String format = DECIMAL_FORMAT.format(value.doubleValue());
        jsonGenerator.writeString(format);
    }
}